package cn.crawler.framework.filter;

import cn.crawler.framework.util.Result;
import cn.crawler.framework.util.param.Param4MapVerify;
import cn.crawler.framework.util.param.ParamValidation;
import cn.crawler.framework.util.param.ParamVerify;
import cn.crawler.framework.util.param.ParamVerifyException;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.JsonFormat;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.ActionContext;
import org.nutz.mvc.ActionFilter;
import org.nutz.mvc.View;
import org.nutz.mvc.view.UTF8JsonView;

import java.lang.reflect.Parameter;

@IocBean(singleton = false)
public class ParamFilter implements ActionFilter {
    private static final Log log = Logs.get();

    @Override
    public View match(ActionContext actionContext) {
        try {
            for (Parameter parameter : actionContext.getMethod().getParameters()) {
                ParamVerify parameterAnnotation = parameter.getAnnotation(ParamVerify.class);
                if (parameterAnnotation != null) {
                    if (parameterAnnotation.required()) {
                        ParamValidation paramValidation = new ParamValidation();
                        //单个参数验证
                        paramValidation.validation(parameterAnnotation, parameter.getName(), actionContext.getRequest().getParameter(parameter.getName()));
                    }
                }
                Param4MapVerify p4MapAnn = parameter.getAnnotation(Param4MapVerify.class);
                if (p4MapAnn != null) {
                    ParamValidation paramValidation = new ParamValidation();
                    if (p4MapAnn.fields().length > 0) {
                        for (ParamVerify paramVerify : p4MapAnn.fields()) {
                            String name = paramVerify.name();
                            if (name.equals("")) {
                                ParamVerifyException.throwNew("the property named 'name' of annotation param in param4map must been not null");
                            }
                            //todo 可能会出现问题
                            paramValidation.validation(paramVerify, name, actionContext.getRequest().getParameter(name));
                        }
                    }
                }
            }
        } catch (ParamVerifyException pe) {
            return new UTF8JsonView(JsonFormat.compact()).setData(Result.error().addCode(-3).addDetail(pe.getMessage()));
        }
        //正常处理下一调用链环节
        return null;
    }
}
